<?php
/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2019/11/5
 * Time: 21:53
 */
class model_api_pdd extends L {

    public static $clientId = 'd861b4e429c44f3887d40fe90c4740d3';
    public static $clientSecret = '7f27aca119bf99f5cad394ba723a785633bd87ca';
    public static $url = "https://gw-api.pinduoduo.com/api/router";

    /**
     * 描述 ：上传商品图片
     * 作者 ：Zoro.Zhu
    **/
    public static function imageUpload($params) {
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.image.upload',
            'timestamp' => time(),
            'image' => $params['image'],
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
//        echo '开始' . time() . '<br>';
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
//        echo '结束' . time() . '<br>';
//        p($res);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['goods_image_upload_response'])){
                return $info['goods_image_upload_response'];
            }else if(!empty($info['error_response'])){
                return $info['error_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：刊登产品到平台
     * 作者 ：Zoro.Zhu
    **/
    public static function productAdd($params){
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.add',
            'timestamp' => time(),
            'second_hand' => 'false',                                             //是否二手商品，true -二手商品 ，false-全新商品
            'is_folt' => 'true',                                                  //是否支持假一赔十，false-不支持，true-支持
            'is_refundable' => 'true',                                            //是否7天无理由退换货，true-支持，false-不支持
            'is_pre_sale' => 'false',                                               //是否预售,true-预售商品，false-非预售商品
            'goods_name' => $params['goods_name'],                                  //标题
            'detail_gallery' => $params['detail_gallery'],                            //详情图
            'carousel_gallery' => $params['carousel_gallery'],                            //轮播图
            'cost_template_id' => $params['cost_template_id'],                     //运费模板ID
            'market_price' => $params['market_price'],                            //市场价（分）
            'cat_id' => $params['cat_id'],                                          //类目ID
            'shipment_limit_second' => $params['shipment_limit_second'],            //承诺发货时间（秒）
            'goods_desc' => $params['goods_desc'],                                  //商品描述， 字数限制：20-500
            'goods_type' => $params['goods_type'],                                  //商品类型
            'country_id' => $params['country_id'],                                  //国家或地区ID（填写海淘商品的货源地），country_id可以通过pdd.goods.country.get获取，仅在goods_type为2、3、4、18时（海淘商品）入参生效，其余goods_type传0
            'sku_list' => $params['sku_list'],                                      //sku列表
            'tiny_name' => $params['tiny_name'],                                    //短标题
            'goods_properties' => $params['goods_properties'],                      //商品属性列表
        );
        //暂时没有上传视频的权限。。。
//        !empty($params['carousel_video']) && $data['carousel_video'] = $params['carousel_video']; //视频
        !empty($params['carousel_video_url']) && $data['carousel_video_url'] = $params['carousel_video_url']; //轮播视频
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
//        p($res);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['goods_add_response'])){
                return $info['goods_add_response'];
            }else if(!empty($info['error_response'])){
                return $info['error_response'];
            }
        }
        return false;

    }

    /**
     * 描述 ：修改产品
     * 作者 ：Zoro.Zhu
     **/
    public static function productUpd($params){
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.information.update',
            'timestamp' => time(),
            'second_hand' => 'false',                                             //是否二手商品，true -二手商品 ，false-全新商品
            'is_folt' => 'true',                                                  //是否支持假一赔十，false-不支持，true-支持
            'is_refundable' => 'true',                                            //是否7天无理由退换货，true-支持，false-不支持
            'is_pre_sale' => 'true',                                               //是否预售,true-预售商品，false-非预售商品
            'pre_sale_time' => strtotime('2020-02-10 23:59:59'),                //预售时间，is_pre_sale为true时必传，UNIX时间戳，只能为某一天的23:59:59
            'goods_id' => $params['goods_id'],                                      //pdd产品Id
            'goods_name' => $params['goods_name'],                                  //标题
            'detail_gallery' => $params['detail_gallery'],                            //详情图
            'carousel_gallery' => $params['carousel_gallery'],                            //轮播图
            'cost_template_id' => $params['cost_template_id'],                     //运费模板ID
            'market_price' => $params['market_price'],                            //市场价（分）
            'cat_id' => $params['cat_id'],                                          //类目ID
            'shipment_limit_second' => $params['shipment_limit_second'],            //承诺发货时间（秒）
            'goods_desc' => $params['goods_desc'],                                  //商品描述， 字数限制：20-500
            'goods_type' => $params['goods_type'],                                  //商品类型
            'country_id' => $params['country_id'],                                  //国家或地区ID（填写海淘商品的货源地），country_id可以通过pdd.goods.country.get获取，仅在goods_type为2、3、4、18时（海淘商品）入参生效，其余goods_type传0
            'sku_list' => $params['sku_list'],                                      //sku列表
            'tiny_name' => $params['tiny_name'],                                    //短标题
            'goods_properties' => $params['goods_properties'],                      //商品属性列表
        );
        !empty($params['carousel_video_url']) && $data['carousel_video_url'] = $params['carousel_video_url']; //轮播视频
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['goods_update_response'])){
                return $info['goods_update_response'];
            }else if(!empty($info['error_response'])){
                return $info['error_response'];
            }
        }
        return false;

    }

    /**
     * 描述 ：删除商品接口,只能删除下架的商品
     * 作者 ：Zoro.Zhu
     **/
    public static function deleteCommit($params){
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.delete.goods.commit',
            'timestamp' => time(),
            'goods_ids' => json_encode($params['goodsId']),                     //商品id 列表(List<Long>) json string，例：[1,2]，一次操作数量请小于50
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
//        p($res);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['open_api_response'])){
                return $info['open_api_response'];
            }else if(!empty($info['error_response'])){
                return $info['error_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：修改商品上下架状态
     * 作者 ：Zoro.Zhu
     **/
    public static function updateSaleStatus($params){
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.sale.status.set',
            'timestamp' => time(),
            'goods_id' => $params['goodsId'],                           //拼多多商品id
            'is_onsale' => $params['isOnsale'],                         //上下架状态：1:上架 0:下架
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['goods_sale_status_set_response'])){
                return $info;
            }else if(!empty($info['error_response'])){
                return $info['error_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：获取商品明细
     * 作者 ：Zoro.Zhu
     **/
    public static function getGoodsDetail($params) {
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.detail.get',
            'timestamp' => time(),
            'goods_id' => $params['goodsId'],
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['goods_detail_get_response'])){
                return $info['goods_detail_get_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：类目预测接口
     * 作者 ：Zoro.Zhu
     **/
    public static function mappingCat($params){
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.outer.cat.mapping.get',
            'timestamp' => time(),
            'outer_cat_id' => $params['catId'],
            'outer_cat_name' => $params['catName'],
            'outer_goods_name' => $params['productName'],
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['outer_cat_mapping_get_response'])){
                return $info['outer_cat_mapping_get_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：获取类目属性
     * 作者 ：Zoro.Zhu
     **/
    public static function getAttrSpec($params) {
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.spec.get',
            'timestamp' => time(),
            'cat_id' => $params['catId'],
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['goods_spec_get_response'])){
                return $info['goods_spec_get_response']['goods_spec_list'];
            }
        }
        return false;
    }

    /**
     * 描述 ：获取类目属性
     * 作者 ：Zoro.Zhu
     **/
    public static function getCatTemp($params) {
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.cat.template.get',
            'timestamp' => time(),
            'cat_id' => $params['cat_id'],
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['open_api_response'])){
                return $info['open_api_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：获取运费模板
     * 作者 ：Zoro.Zhu
     **/
    public static function getLogisticsTemp($params){
        $key = 'logisticsTemp' . $params['account'];
        $info = '[]';
        if(of_base_com_kv::get($key)){
            $info = of_base_com_kv::get($key);
        }else{
            $data = array (
                'access_token' => $params['accessToken'],
                'client_id' => $params['clientId'],
                'data_type' => 'JSON',
                'type' => 'pdd.goods.logistics.template.get',
                'timestamp' => time(),
            );
            $sign = self::getSign($data, $params['clientSecret']);
            $data['sign'] = $sign;
            $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
            if(!empty($res['state'])){
                $info = json_decode($res['response'], true);
                if(!empty($info['goods_logistics_template_get_response'])){
                    $list = $info['goods_logistics_template_get_response']['logistics_template_list'];
                    $info = json_encode($list);
                    of_base_com_kv::set($key, $info, 86400 * 7);
                }
            }
        }
        $data = json_decode($info, true);
        return $data;
    }

    /**
     * 描述 ：查看快递公司信息
     * 作者 ：Zoro.Zhu
     **/
    public static function getLogisticsCompanies($params){
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.logistics.companies.get',
            'timestamp' => time(),
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['logistics_companies_get_response'])){
                return $info['logistics_companies_get_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：获取运费模板
     * 作者 ：Zoro.Zhu
     **/
    public static function getCats($params){
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.authorization.cats',
            'timestamp' => time(),
            'parent_cat_id' => $params['parent_cat_id'],
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['goods_auth_cats_get_response'])){
                return $info['goods_auth_cats_get_response'];
            }
        }
        return false;
    }


    /**
     * 描述 ：获取运费模板
     * 作者 ：Zoro.Zhu
     **/
    public static function getSpec($params){
//        p($params);exit;
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.goods.spec.id.get',
            'timestamp' => time(),
            'parent_spec_id' => $params['parent_spec_id'],
            'spec_name' => $params['spec_name'],
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
//        p($res);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['goods_spec_id_get_response'])){
                return $info['goods_spec_id_get_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：抓取订单
     * 作者 ：Zoro.Zhu
    **/
    public static function getOrderList($params) {
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.order.list.get',
            'timestamp' => time(),
            'order_status' => '1',
            'refund_status' => '5',
            'start_confirm_at' => $params['stateDate'],                             //成团开始时间戳
            'end_confirm_at' => $params['endDate'],                                 //成团结束时间戳
            'page' => $params['page'],
            'page_size' => '100'
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        p($res);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['order_list_get_response'])){
                return $info['order_list_get_response'];
            }
        }
        return false;
    }

    /**
     * 描述 ：订单发货通知
     * 作者 ：Zoro.Zhu
     **/
    public static function orderSend($params) {
        $data = array (
            'access_token' => $params['accessToken'],
            'client_id' => $params['clientId'],
            'data_type' => 'JSON',
            'type' => 'pdd.logistics.online.send',
            'timestamp' => time(),
            'logistics_id' => $params['logistics_id'],                          //物流公司ID
            'order_sn' => $params['order_sn'],                                  //订单号
            'tracking_number' => $params['tracking_number'],                    //物流单号
        );
        $sign = self::getSign($data, $params['clientSecret']);
        $data['sign'] = $sign;
        $res = of_base_com_net::request(self::$url, ['post' => json_encode($data), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            $info = json_decode($res['response'], true);
            if(!empty($info['logistics_online_send_response'])){
                return $info['logistics_online_send_response'];
            }else if($info['error_response']['error_msg'] == '订单已发货'){
                return ['is_success' => true];
            }else if(!empty($info['error_response']['error_msg'])){
                return $info['error_response']['error_msg'];
            }
        }
        return false;
    }

    /**
     * 描述 ：获取授权code的url拼接
     * 作者 ：Zoro.Zhu
    **/
    public static function codeUrl($account){
        $token = model_vsAccount::getAccountToken(['account' => $account]);
        of_base_com_kv::set('accreditAccount' , json_encode($token), 3600);
        $serverUrl = 'http://' . $_SERVER['SERVER_NAME'];
        if(!empty($_SERVER["SERVER_PORT"])){
            $serverUrl .= ':' . $_SERVER["SERVER_PORT"];
        } else {
            $serverUrl .= '/vs';
        }
        $serverUrl .= "/serv/accreditPdd.php";
        $utl = "https://mms.pinduoduo.com/open.html?response_type=code&client_id=" . $token['appKey'] . "&redirect_uri=" . $serverUrl;
        return $utl;
    }

    /**
     * 描述 : 刷新token
     * 作者 : Zoro.Zhu
    **/
    public static function refreshToken($data) {
        $url = "http://open-api.pinduoduo.com/oauth/token";
        $info['grant_type'] = 'refresh_token';
        $info['client_id'] = $data['appKey'];
        $info['client_secret'] = $data['appSecret'];
        $info['refresh_token'] = $data['refreshToken'];
        $res = of_base_com_net::request($url, ['post' => json_encode($info), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            return json_decode($res['response'], true);
        }else if($data['retry'] < 3){
            //重试3次
            $data['retry'] = !empty($data['retry']) ? $data['retry'] + 1 : 1;
            self::refreshToken($data);
        }else{
            return [];
        }
    }

    /**
     * 描述 : 通过code获取token
     * 作者 : Zoro.Zhu
     **/
    public static function codeToken($code, $clientId, $secret) {
        $url = "http://open-api.pinduoduo.com/oauth/token";
        $info['grant_type'] = 'authorization_code';
        $info['client_id'] = $clientId;
        $info['client_secret'] = $secret;
        $info['code'] = $code;
        $res = of_base_com_net::request($url, ['post' => json_encode($info), 'header' => ['Content-Type: application/json']]);
        if(!empty($res['state'])){
            return json_decode($res['response'], true);
        }else{
            return [];
        }
    }

    /**
     * 描述：按照拼多多接口的要求整理数据
     * 作者：Zoro.Zhu
     **/
    public static function arrangementData($data, $Secret) {
        ksort($data);
        $str = $Secret;
        $info = '';
        foreach ($data as $key => $val) {
            $str .= $key.$val;
            $info .= "{$key}={$val}&";
        }
        $str .= $Secret;
        $sign = strtoupper(MD5($str));
        $info .= "sign={$sign}";
        return $info;
    }

    /**
     * 描述：计算签名
     * 作者：Zoro.Zhu
     **/
    public static function getSign($data,$Secret){
        ksort($data);
        $str = $Secret;
        foreach ($data as $key => $val) {
            $str .= $key.$val;
        }
        $str .= $Secret;
        $sign = strtoupper(MD5($str));
        return $sign;
    }

}
return true;